﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
using Newtonsoft.Json;
using System.Diagnostics;
namespace Growatt.ShinebusServiceUploadPack.Service.FeishuHelper
{

    namespace Growatt.Shinebus.UI.AutoCal
    {
        public class TokenHelper
        {
            private const string TokenUrl = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal";
            private string accessToken;
            private DateTime tokenExpireTime; // 存储 token 过期时间

            public string GetTenantAccessToken(string appId, string appSecret)
            {
                // 如果 token 已存在且未过期，则返回已有的 token
                if (!string.IsNullOrEmpty(accessToken) && DateTime.UtcNow < tokenExpireTime)
                {
                    return accessToken;
                }

                var client = new RestClient(TokenUrl);
                var request = new RestRequest();
                request.Method = Method.Post;
                request.AddHeader("Content-Type", "application/json; charset=utf-8");

                // 构建请求体
                var requestBody = new
                {
                    app_id = appId,
                    app_secret = appSecret
                };

                request.AddJsonBody(requestBody);

                var response = client.Execute(request);

                if (response.IsSuccessful)
                {
                    var responseData = JsonConvert.DeserializeObject<TenantAccessTokenResponse>(response.Content);

                    if (responseData.code == 0)
                    {
                        accessToken = responseData.tenant_access_token;
                        tokenExpireTime = DateTime.UtcNow.AddSeconds(responseData.expire); // 设置过期时间
                        Debug.WriteLine("获取 tenant_access_token 成功。");
                        return accessToken;
                    }
                    else
                    {
                        Debug.WriteLine($"获取失败: {responseData.code} - {responseData.msg}");
                    }
                }
                else
                {
                    Debug.WriteLine($"请求失败: {response.StatusCode} - {response.Content}");
                }

                return null;
            }
        }

        public class FeishuAPIHelper
        {

            string FeishuAPIHelper_app_id = "cli_a7ea5c4ed83d900d";
            string FeishuAPIHelper_app_secret = "1kXpE9MgCVHLNOY8hdHJ4cLdbYRy7762";
            private readonly TokenHelper tokenHelper;

            public FeishuAPIHelper()
            {
                tokenHelper = new TokenHelper();
            }
            public void GetTenantAccessToken()
            {
                var apiHelper = new FeishuAPIHelper();
                string accessToken = apiHelper.tokenHelper.GetTenantAccessToken(FeishuAPIHelper_app_id, FeishuAPIHelper_app_secret);
                Debug.WriteLine($"获取的 Tenant Access Token: {accessToken}");
            }
            /// <summary>
            /// 获取用户 ID
            /// </summary>
            /// <param name="emailsList"></param>
            /// <param name="mobilesList"></param>
            public List<string> BatchGetUserId(List<string> emailsList, List<string> mobilesList)
            {
                var apiHelper = new FeishuAPIHelper();
                string accessToken = apiHelper.tokenHelper.GetTenantAccessToken(FeishuAPIHelper_app_id, FeishuAPIHelper_app_secret);

                var client = new RestClient("https://open.feishu.cn/open-apis/contact/v3/users/batch_get_id");
                var request = new RestRequest();
                request.Method = Method.Post;
                request.AddHeader("Authorization", $"Bearer {accessToken}");
                request.AddHeader("Content-Type", "application/json");

                var body = new
                {
                    emails = emailsList,
                    include_resigned = true,
                    mobiles = mobilesList
                };

                request.AddJsonBody(body);

                var response = client.Execute(request);

                if (response.IsSuccessful)
                {
                    Debug.WriteLine("请求成功!");
                    Debug.WriteLine("返回内容: ");
                    Debug.WriteLine(response.Content);
                    ApiResponseUser apiResponse = JsonConvert.DeserializeObject<ApiResponseUser>(response.Content);
                    return apiResponse.data.user_list.Select(o => o.user_id).ToList();
                }
                else
                {
                    Debug.WriteLine($"请求失败! 状态码: {response.StatusCode}, 错误信息: {response.ErrorMessage}");
                    return new List<string>();
                }
            }
            /// <summary>
            /// 发送消息
            /// </summary>
            /// <param name="receiveId"></param>
            /// <param name="content"></param>
            public string SendMessage(string receiveId, string content)
            {
                var apiHelper = new FeishuAPIHelper();
                string accessToken = apiHelper.tokenHelper.GetTenantAccessToken(FeishuAPIHelper_app_id, FeishuAPIHelper_app_secret);

                var client = new RestClient("https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=open_id");
                var request = new RestRequest();
                request.Method = Method.Post;
                request.AddHeader("Authorization", $"Bearer {accessToken}");
                request.AddHeader("Content-Type", "application/json");

                var body = new
                {
                    content = JsonConvert.SerializeObject(new { text = content }),
                    msg_type = "text",
                    receive_id = receiveId
                };

                request.AddJsonBody(body);

                var response = client.Execute(request);

                if (response.IsSuccessful)
                {
                    Debug.WriteLine("请求成功!");
                    Debug.WriteLine("返回内容: ");
                    Debug.WriteLine(response.Content);
                    // 反序列化 JSON 字符串
                    ApiResponseMessage apiResponse = JsonConvert.DeserializeObject<ApiResponseMessage>(response.Content);
                    return apiResponse.data.message_id;
                }
                else
                {
                    Debug.WriteLine($"请求失败! 状态码: {response.StatusCode}, 错误信息: {response.ErrorMessage}");
                    return string.Empty;
                }
            }
            /// <summary>
            /// 发送紧急电话
            /// </summary>
            /// <param name="messageId"></param>
            /// <param name="userIdList"></param>
            /// <param name="userIdType"></param>
            public SendUrgentPhoneResponse SendUrgentPhone(string messageId, List<string> userIdList, string userIdType = "open_id")
            {
                string accessToken = tokenHelper.GetTenantAccessToken(FeishuAPIHelper_app_id, FeishuAPIHelper_app_secret);
                string BaseUrl = "https://open.feishu.cn/open-apis/im/v1/messages/";

                var client = new RestClient(BaseUrl);
                var request = new RestRequest($"{messageId}/urgent_phone?user_id_type={userIdType}", Method.Patch);
                request.AddHeader("Authorization", $"Bearer {accessToken}");
                request.AddHeader("Content-Type", "application/json; charset=utf-8");

                var payload = new
                {
                    user_id_list = userIdList
                };

                request.AddJsonBody(payload);

                var response = client.Execute(request);

                if (response.IsSuccessful)
                {
                    Debug.WriteLine("紧急电话请求已成功发送。");
                    Debug.WriteLine("响应内容: " + response.Content);
                    // 反序列化 JSON 字符串
                    SendUrgentPhoneResponse apiResponse = JsonConvert.DeserializeObject<SendUrgentPhoneResponse>(response.Content);
                }
                else
                {
                    Debug.WriteLine($"请求失败: {response.StatusCode} - {response.Content}");
                }
                return null;

            }

            /// <summary>
            /// 发送紧急短息
            /// </summary>
            /// <param name="messageId"></param>
            /// <param name="userIdList"></param>
            /// <param name="userIdType"></param>
            public SendUrgentPhoneResponse SendUrgent_sms(string messageId, List<string> userIdList, string userIdType = "open_id")
            {
                string accessToken = tokenHelper.GetTenantAccessToken(FeishuAPIHelper_app_id, FeishuAPIHelper_app_secret);
                string BaseUrl = "https://open.feishu.cn/open-apis/im/v1/messages/";

                var client = new RestClient(BaseUrl);
                var request = new RestRequest($"{messageId}/urgent_sms?user_id_type={userIdType}", Method.Patch);
                request.AddHeader("Authorization", $"Bearer {accessToken}");
                request.AddHeader("Content-Type", "application/json; charset=utf-8");

                var payload = new
                {
                    user_id_list = userIdList
                };

                request.AddJsonBody(payload);

                var response = client.Execute(request);

                if (response.IsSuccessful)
                {
                    Debug.WriteLine("紧急电话请求已成功发送。");
                    Debug.WriteLine("响应内容: " + response.Content);
                    // 反序列化 JSON 字符串
                    SendUrgentPhoneResponse apiResponse = JsonConvert.DeserializeObject<SendUrgentPhoneResponse>(response.Content);
                }
                else
                {
                    Debug.WriteLine($"请求失败: {response.StatusCode} - {response.Content}");
                }
                return null;
            }
        }

        public class FeishuAPIHelperUsage
        {

            public bool SendUrgentPhoneUrl(List<string> emailsList, String sendString)
            {
                bool isSuccess = false;
                var list = new FeishuAPIHelper().BatchGetUserId(emailsList, new List<string>());
                if (list?.Count > 0)
                {

                    var message_id = new FeishuAPIHelper().SendMessage(list[0], sendString);
                    if (!string.IsNullOrEmpty(message_id))
                    {
                        SendUrgentPhoneResponse SendUrgentPhone_result = new FeishuAPIHelper().SendUrgentPhone(message_id, new List<string>() { list[0] });
                        if (SendUrgentPhone_result?.data?.invalid_user_id_list?.Count == 0)
                            isSuccess = true;

                    }
                }
                return isSuccess;
            }

            public bool SendUrgentMessageUrl(List<string> emailsList, String sendString)
            {
                bool isSuccess = false;
                var list = new FeishuAPIHelper().BatchGetUserId(emailsList, new List<string>());
                if (list?.Count > 0)
                {

                    var message_id = new FeishuAPIHelper().SendMessage(list[0], sendString);
                    if (!string.IsNullOrEmpty(message_id))
                    {
                        SendUrgentPhoneResponse SendUrgentPhone_result = new FeishuAPIHelper().SendUrgent_sms(message_id, new List<string>() { list[0] });
                        if (SendUrgentPhone_result?.data?.invalid_user_id_list?.Count == 0)
                            isSuccess = true;

                    }
                }
                return isSuccess;
            }

            public bool SendMessageUrl(List<string> emailsList, String sendString)
            {
                bool isSuccess = false;
                var list = new FeishuAPIHelper().BatchGetUserId(emailsList, new List<string>());
                if (list?.Count > 0)
                {

                    var message_id = new FeishuAPIHelper().SendMessage(list[0], sendString);
                    if (!string.IsNullOrEmpty(message_id))
                        isSuccess = true;
                }
                return isSuccess;
            }
        }

        // 用于反序列化响应的类
        public class TenantAccessTokenResponse
        {
            public int code { get; set; }
            public string msg { get; set; }
            public string tenant_access_token { get; set; }
            public int expire { get; set; }
        }


        #region 获取ID返回
        public class ApiResponseUser
        {
            public int code { get; set; }
            public Data data { get; set; }
            public string msg { get; set; }
        }

        public class Data
        {
            public List<UserInformation> user_list { get; set; }
        }

        public class UserInformation
        {
            public string email { get; set; }
            public StatusUser status { get; set; }
            public string user_id { get; set; }
        }

        public class StatusUser
        {
            public bool is_activated { get; set; }
            public bool is_exited { get; set; }
            public bool is_frozen { get; set; }
            public bool is_resigned { get; set; }
            public bool is_unjoin { get; set; }
        }
        #endregion

        #region 发送消息返回
        public class ApiResponseMessage
        {
            public int code { get; set; }
            public MessageData data { get; set; }
            public string msg { get; set; }
        }

        public class MessageData
        {
            public MessageBody body { get; set; }
            public string chat_id { get; set; }
            public string create_time { get; set; }
            public bool deleted { get; set; }
            public string message_id { get; set; }
            public string msg_type { get; set; }
            public SenderInfo sender { get; set; }
            public string update_time { get; set; }
            public bool updated { get; set; }
        }

        public class MessageBody
        {
            public string content { get; set; }
        }

        public class SenderInfo
        {
            public string id { get; set; }
            public string id_type { get; set; }
            public string sender_type { get; set; }
            public string tenant_key { get; set; }
        }

        #endregion

        #region 发送紧急电话
        public class SendUrgentPhoneResponse
        {
            public int code { get; set; }
            public SendUrgentPhoneData data { get; set; }
            public string msg { get; set; }
        }

        public class SendUrgentPhoneData
        {
            public List<string> invalid_user_id_list { get; set; }
        }
        #endregion

    }



}
